package com.qiyun.asyncarrange;

import java.util.concurrent.*;

public class CompletableFutureTest07 {

    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
            200,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(100000),
            Executors.defaultThreadFactory(),//默认线程工厂
            new ThreadPoolExecutor.AbortPolicy()//拒绝策略
            //如果不想抛弃还要执行。可以使用new ThreadPoolExecutor.CallerRunsPolicy()
    );

    /**
     * 线程串行化
     *
     * @param args
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
         * public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
         */

        /*
            1.多任务组合
        */
        CompletableFuture<String> futureImg = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品的图片");
            return "hello.jpg";
        }, executor);

        CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("查询商品的属性");

            return "黑色  256G";
        }, executor);

        CompletableFuture<String> futureDesc = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品的介绍");
            return "华为";
        }, executor);

        /*
        allOf：等待所有任务完成
         */
    /*   CompletableFuture<Void> allOf = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
        allOf.get();*/


        /*
        anyOf：只要有一个任务完成,
         */
        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(futureImg, futureAttr, futureDesc);

        anyOf.get();


        System.out.println("main...end...");

        /*
        这是不正确的，这种写法他们三个是串行的，一个一个执行完的，没有并行执行
         */
        /*futureImg.get();
        futureAttr.get();
        futureDesc.get();*/


    }

}
